from flask import request
from flask_restx import Resource, Namespace, fields
from app.utils.response import success_response, error_response, paginate_response
from app.utils.auth import token_required
from app.utils.validators import validate_required_fields, validate_email, validate_phone
from app.services.department_service import DepartmentService
from app.swagger_docs import (
    success_response_model, error_response_model, pagination_response_model,
    department_model
)

# 创建部门命名空间
dept_ns = Namespace('departments', description='部门管理接口')

# 定义请求模型
dept_create_model = dept_ns.model('DepartmentCreate', {
    'name': fields.String(required=True, description='部门名称'),
    'description': fields.String(description='部门描述'),
    'parent_id': fields.Integer(description='父级部门ID'),
    'sort': fields.Integer(description='排序', default=0),
    'status': fields.Boolean(description='状态', default=True),
    'leader': fields.String(description='部门负责人'),
    'phone': fields.String(description='联系电话'),
    'email': fields.String(description='邮箱地址')
})

dept_update_model = dept_ns.model('DepartmentUpdate', {
    'name': fields.String(description='部门名称'),
    'description': fields.String(description='部门描述'),
    'parent_id': fields.Integer(description='父级部门ID'),
    'sort': fields.Integer(description='排序'),
    'status': fields.Boolean(description='状态'),
    'leader': fields.String(description='部门负责人'),
    'phone': fields.String(description='联系电话'),
    'email': fields.String(description='邮箱地址')
})

@dept_ns.route('/')
class DepartmentListAPI(Resource):
    """部门列表和新增接口"""
    
    @dept_ns.doc(
        description='获取部门列表（支持树形结构）',
        security='Bearer',
        params={
            'tree': '是否返回树形结构 (true/false)',
            'page': '页码（非树形结构时使用）',
            'per_page': '每页数量（非树形结构时使用）',
            'keyword': '搜索关键词',
            'status': '状态筛选 (0:禁用, 1:启用)'
        },
        responses={
            200: ('获取成功', success_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin):
        """获取部门列表"""
        # 检查是否需要树形结构
        tree = request.args.get('tree', type=bool)
        if tree:
            data = DepartmentService.get_tree()
            return success_response(data)
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        keyword = request.args.get('keyword', '')
        status = request.args.get('status', type=int)
        
        if status is not None:
            status = bool(status)
        
        query, page, per_page = DepartmentService.get_list(page, per_page, keyword, status)
        return paginate_response(query, page, per_page)
    
    @dept_ns.doc(
        description='创建新部门',
        security='Bearer',
        responses={
            200: ('创建成功', success_response_model),
            400: ('请求参数错误', error_response_model),
            401: ('未授权', error_response_model),
            500: ('服务器错误', error_response_model)
        }
    )
    @dept_ns.expect(dept_create_model, validate=True)
    @token_required
    def post(self, current_admin):
        """创建新部门"""
        # 验证必填字段
        is_valid, error_msg = validate_required_fields(['name'])
        if not is_valid:
            return error_response(error_msg, 400)
        
        data = request.get_json()
        
        # 验证邮箱格式
        if data.get('email') and not validate_email(data.get('email')):
            return error_response('邮箱格式不正确', 400)
        
        # 验证手机号格式
        if data.get('phone') and not validate_phone(data.get('phone')):
            return error_response('手机号格式不正确', 400)
        
        try:
            department = DepartmentService.create(data)
            return success_response(department.to_dict(), '创建成功')
        except Exception as e:
            return error_response(f'创建失败：{str(e)}', 500)


@dept_ns.route('/<int:dept_id>')
class DepartmentDetailAPI(Resource):
    """部门详情、更新和删除接口"""
    
    @dept_ns.doc(
        description='获取部门详情',
        security='Bearer',
        responses={
            200: ('获取成功', success_response_model),
            404: ('部门不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin, dept_id):
        """获取部门详情"""
        department = DepartmentService.get_by_id(dept_id)
        if not department:
            return error_response('部门不存在', 404)
        
        return success_response(department.to_dict())
    
    @dept_ns.doc(
        description='更新部门信息',
        security='Bearer',
        responses={
            200: ('更新成功', success_response_model),
            400: ('请求参数错误', error_response_model),
            404: ('部门不存在', error_response_model),
            401: ('未授权', error_response_model),
            500: ('服务器错误', error_response_model)
        }
    )
    @dept_ns.expect(dept_update_model)
    @token_required
    def put(self, current_admin, dept_id):
        """更新部门信息"""
        department = DepartmentService.get_by_id(dept_id)
        if not department:
            return error_response('部门不存在', 404)
        
        data = request.get_json()
        
        # 验证邮箱格式
        if data.get('email') and not validate_email(data.get('email')):
            return error_response('邮箱格式不正确', 400)
        
        # 验证手机号格式
        if data.get('phone') and not validate_phone(data.get('phone')):
            return error_response('手机号格式不正确', 400)
        
        try:
            updated_department = DepartmentService.update(dept_id, data)
            return success_response(updated_department.to_dict(), '更新成功')
        except Exception as e:
            return error_response(f'更新失败：{str(e)}', 500)
    
    @dept_ns.doc(
        description='删除部门',
        security='Bearer',
        responses={
            200: ('删除成功', success_response_model),
            400: ('删除失败', error_response_model),
            404: ('部门不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def delete(self, current_admin, dept_id):
        """删除部门"""
        result = DepartmentService.delete(dept_id)
        if isinstance(result, tuple):
            success, message = result
            if not success:
                return error_response(message, 400)
            return success_response(message=message)
        else:
            if not result:
                return error_response('删除失败，部门不存在', 404)
            return success_response(message='删除成功')


@dept_ns.route('/options')
class DepartmentOptionsAPI(Resource):
    """部门选项数据接口"""
    
    @dept_ns.doc(
        description='获取部门选项数据（用于创建子部门时选择父部门）',
        security='Bearer',
        responses={
            200: ('获取成功', success_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin):
        """获取部门选项数据"""
        data = DepartmentService.get_parent_options()
        return success_response(data) 